<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
			<el-form-item label="店铺名称" prop="storeIds" style="width:250px">
				<!-- <el-input v-model="queryParams.storeName" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" /> -->
				<el-tree-select check-strictly v-model="queryParams.storeIds" :data="deptOptions"
                                :props="{ value: 'storeId', label: 'storeName', children: 'children' }" value-key="storeId"
                                style="width: 100%;" placeholder="请选择归属门店" filterable clearable multiple/>
			</el-form-item>
			<el-form-item label="产品名称" prop="contentName" style="width:250px">
				<el-input v-model="queryParams.contentName" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
			</el-form-item>

			<el-form-item label="打印编号" prop="printNum" style="width:250px">
				<el-input v-model="queryParams.printNum" placeholder="请输入打印编号" clearable @keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="标签状态" prop="labelStatus" style="width:250px">
				<el-select v-model="queryParams.labelStatus" placeholder="请输入标签状态" clearable @change="handleQuery">
					<el-option v-for="dict in labelStatusList" :key="dict.value" :label="dict.label"
						:value="dict.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="标签类别" prop="labelClassify" style="width:250px">
				<el-select v-model="queryParams.labelClassify" placeholder="请选择标签类别" clearable @change="handleQuery">
					<el-option v-for="dict in content_label_type" :key="dict.value" :label="dict.label"
						:value="dict.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="打印时间" prop="time">
				<el-date-picker v-model="queryParams.starTime" value-format="x" type="datetimerange" :shortcuts="shortcuts" range-separator="至"
					start-placeholder="开始时间" end-placeholder="结束时间" @change="handleQuery"/>
			</el-form-item>
			<el-form-item label="过期时间" prop="time">
				<el-date-picker v-model="queryParams.endTime" value-format="x" type="datetimerange" :shortcuts="shortcuts" range-separator="至"
					start-placeholder="开始时间" end-placeholder="结束时间" @change="handleQuery"/>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
				<el-button icon="Refresh" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="danger" size="small" icon="Delete" :disabled="multiple" @click="handleDelete"
					v-hasPermi="['manage:history:remove']">删除</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="warning" size="small" icon="Download" @click="handleExport"
					v-hasPermi="['manage:history:export']">导出</el-button>
			</el-col>
			<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table border v-loading="loading" :data="historyList" @selection-change="handleSelectionChange"
			@row-click="(row) => (console.log(row))">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="序号" type="index" width="60" align="center" />
			<el-table-column label="产品ID" width="80" align="center" prop="contentId" />
			<el-table-column label="打印编号" width="100" align="center" prop="printNum" />
			<el-table-column label="门店名称" width="100" align="center" prop="storeName" />
			<el-table-column label="产品名称" width="100"  align="center" prop="contentName" />
			<el-table-column label="标签状态" align="center" prop="labelStatus" />
			<el-table-column label="标签类型" width="100"  align="center" prop="labelClassify">
				<template #default="scope">
					<dict-tag type="default" :options="content_label_type" :value="scope.row.labelClassify" />
				</template>
			</el-table-column>
			<el-table-column label="标签来源" width="100"  align="center" prop="labelSource">
				<template #default="scope">
					{{ scope.row.labelSource === '0' ? '手动打印' : '补打' }}
				</template>
			</el-table-column>
			<!-- <el-table-column label="剩余时间" align="center" prop="residueTime" /> -->
			<el-table-column label="打印人" width="100"  align="center" prop="printUser" />
			<el-table-column label="处理人" width="100"  align="center" prop="processedUser">
				<template #default="scope">
					<span>
						{{ scope.row.processedUser || '--' }}
					</span>
				</template>
			</el-table-column>
			
			<el-table-column label="份数" align="center" prop="unitNum" />
			<el-table-column label="打印时间" align="center" prop="printTime" width="180" />
			<el-table-column label="到期时间" align="center" prop="expireTime" width="180" />
			<el-table-column label="处理时间" align="center" prop="processedTime" width="180" />
			<el-table-column label="处理时间对比" align="center" prop="diffTime" width="180" />
			<!-- <el-table-column label="解冻时间" align="center" prop="thawTime" width="180" /> -->
			<el-table-column label="保存方法" align="center" prop="saveMethodContent" />
			<el-table-column label="保质期" align="center" prop="qualityPeriod">
				<template #default="scope">
					<span>
						{{ scope.row.qualityPeriod }}{{ scope.row.dateType }}
					</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" v-hasPermi="['manage:history:remove']">
				<template #default="scope">
					<el-link icon="Delete" class="table_link_btn" type="danger" :underline="false"
						@click="handleDelete(scope.row)" v-hasPermi="['manage:history:remove']">
						<span class="table_link_text">删除</span>
					</el-link>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize" @pagination="getList" />

	</div>
</template>

<script setup name="History" lang="ts">
import { listHistory, getHistory, delHistory, addHistory, updateHistory } from '@/api/manage/history';
import { easyListStore, listStore } from '@/api/system/store';
import { dayjs } from 'element-plus';
// import dayjs from 'dayjs';
import { getCurrentInstance, ref } from 'vue';

const { proxy } = getCurrentInstance() as any;

const historyList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<any>([]);
const names = ref<any>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const queryRef = ref();
const {content_label_type} = proxy.useDict('content_label_type');
const form = ref<any>({});
const queryParams = ref({
	storeIds:[],
	pageNum: 1,
	pageSize: 10,
	contentName: null,
	printNum: null,
	labelStatus: '',
	starTime: '',
	endTime: '',
	storeName:'',
	labelClassify:''
});
const shortcuts = [
	{
		text: '最近一周',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
			return [start, end];
		},
	},
	{
		text: '最近一个月',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
			return [start, end];
		},
	},
	{
		text: '最近三个月',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
			return [start, end];
		},
	},
];
const labelStatusList = [{ label: '保鲜中', value: '1' }, { label: '即将过期', value: '2' }, { label: '已过期', value: '3' }, { label: '已用完', value: '4' }, { label: '报损', value: '5' }, { label: '其他', value: '6' }];
/** 查询打印记录列表 */
function getList() {
	loading.value = true;
	let query=null;
	query = queryParams.value;

	if(queryParams.value.starTime){
		query = { ...query, printTimeBegin: queryParams.value.starTime[0], printTimeEnd: queryParams.value.starTime[1] };
	}
	if(queryParams.value.endTime){
		query = { ...query, expireTimeBegin: queryParams.value.endTime[0], expireTimeEnd: queryParams.value.endTime[1] };
	}
	console.log(queryParams.value,query,'-----');
	listHistory(query).then((response: any) => {
		historyList.value = response.data.list.map((ele: any) => {
			return {
				...ele,
				printNum: `#${ele.printNum}`,
				printTime: !ele.printTime ? '--' :dayjs(+ele.printTime).format('YYYY-MM-DD HH:mm:ss'),
				expireTime: !ele.expireTime ? '--' :dayjs(+ele.expireTime).format('YYYY-MM-DD HH:mm:ss'),
				processedTime: !ele.processedTime ? '--' :dayjs(+ele.processedTime).format('YYYY-MM-DD HH:mm:ss'),
				diffTime:ele.processedTime ? (ele.processedTime - ele.expireTime > 0 ? '过期后处理' : '过期前处理'):'未处理',
				thawTime: !ele.thawTime ? '--' : dayjs(+ele.thawTime).format('YYYY-MM-DD HH:mm:ss'),
				labelStatus: labelStatusList.find(label => label.value === ele.labelStatus)?.label || '--'
			};
		});
		total.value = response.data.total;
		loading.value = false;
	});
}

// 表单重置
function reset() {
	form.value = {
		id: null, contentId: null, storeIds: null, storeName: null, labelStatus: '', thawTime: null, contentName: null, residueTime: null, printUser: null, unitNum: null, labelClassify: null, printTime: null, earlyWarning: null, expireTime: null, printNum: null, saveMethodContent: null, qualityPeriod: null, handleStatus: '0', templateCorrespondingData: null
	};
	proxy.resetForm('historyRef');
}

/** 搜索按钮操作 */
function handleQuery() {
	queryParams.value.pageNum = 1;
	getList();
}

/** 重置按钮操作 */
function resetQuery() {
	proxy.resetForm(queryRef);
	handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection: any) {
	ids.value = selection.map((item: any) => item.id);
	names.value = selection.map((item: any) => item.printNum);
	single.value = selection.length !== 1;
	multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
	reset();
	open.value = true;
	title.value = '添加打印记录';
}

/** 修改按钮操作 */
function handleUpdate(row: any) {
	reset();
	const id = row.id || ids.value;
	getHistory(id).then(response => {
		form.value = response.data;
		open.value = true;
		title.value = '修改打印记录';
	});
}

/** 提交按钮 */
function submitForm() {
	proxy.$refs['historyRef'].validate((valid: boolean) => {
		if (valid) {
			if (form.value.id != null) {
				updateHistory(form.value).then(response => {
					proxy.$modal.msgSuccess('修改成功');
					open.value = false;
					getList();
				});
			} else {
				addHistory(form.value).then(response => {
					proxy.$modal.msgSuccess('新增成功');
					open.value = false;
					getList();
				});
			}
		}
	});
}

/** 删除按钮操作 */
function handleDelete(row: any) {
	const idList = row.id || ids.value;
	const namesList = row.printNum || names.value;
	proxy.$modal.confirm('是否确认删除打印记录编号为"' + namesList + '"的数据项？')
		.then(() => {
			return delHistory(idList);
		}).then(() => {
			getList();
			proxy.$modal.msgSuccess('删除成功');
		}).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
	proxy.download('manage/history/exportByStream', {
		...queryParams.value
	}, `history_${new Date().getTime()}.xlsx`);
}
const deptOptions= ref([]);

const getTreeselect = async () => {
	const storeRes = await easyListStore({});
	console.log(storeRes,'门店下拉结构');
	deptOptions.value = proxy.handleTree(storeRes.data, 'storeId');
};
getList();
getTreeselect();
</script>
